package com.lg.okframe;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.lg.okframe.activity.CustomView;
import com.lg.okframe.base.BaseActivity;
import com.lg.okframe.base.BaseFragment;
import com.lg.okframe.fragment.ForumFragment;
import com.lg.okframe.fragment.HomeFragment;
import com.lg.okframe.fragment.RecruitFragment;
import com.lg.okframe.fragment.StudyFragment;
import com.lg.okframe.fragment.UserFragment;
import com.lg.okframe.study.communication.Children1;
import com.lg.okframe.study.communication.FunctionManager;
import com.lg.okframe.utils.view.BootomTabUtils;
import com.lg.okframe.view.ResideLayout;
import com.lg.okframe.view.SlidingMenu;
import com.tangxiaolv.telegramgallery.GalleryActivity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;

import static com.tangxiaolv.telegramgallery.Utils.AndroidUtilities.showToast;

public class MainActivity extends BaseActivity implements GestureDetector.OnGestureListener, View.OnTouchListener {
    private FrameLayout frame;
    private HomeFragment home_fragment;
    private ForumFragment catory_fragment;
    private FragmentManager supportFragmentManager;
    private UserFragment userFragment;
    private RecruitFragment liveFragment;
    private StudyFragment studyFragment;
    private LinearLayout tilebar_view;
    private File file;
    private ResideLayout resideLayout;
    private GestureDetector mGestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int setMainView() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {

        //加载fragment
        supportFragmentManager = getSupportFragmentManager();
        home_fragment = new HomeFragment();
        liveFragment = new RecruitFragment(); //招聘
        studyFragment = new StudyFragment(); //学习
        catory_fragment = new ForumFragment(); //论坛
        userFragment = new UserFragment();
        supportFragmentManager.beginTransaction().add(R.id.frame, home_fragment, "tag3").show(home_fragment).commit();
        supportFragmentManager.beginTransaction().add(R.id.frame, liveFragment, "tag1").hide(liveFragment).commit();
        supportFragmentManager.beginTransaction().add(R.id.frame, catory_fragment, "tag32").hide(catory_fragment).commit();
        supportFragmentManager.beginTransaction().add(R.id.frame, userFragment, "tag33").hide(userFragment).commit();
        supportFragmentManager.beginTransaction().add(R.id.frame, studyFragment, "tag33").hide(studyFragment).commit();
//        supportFragmentManager.beginTransaction().add(R.id.frame, userFragment, "tag33").hide(userFragment).commit();
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        initBootomUI(); //绘制底部UI
        final VideoView video_view = (VideoView) findViewById(R.id.video_view);
        resideLayout = (ResideLayout) findViewById(R.id.resideLayout);

        video_view.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/raw/vv"));

        MediaController mediaController = new MediaController(this);
        mediaController.setVisibility(View.GONE); //设置隐藏
        video_view.setMediaController(mediaController);
        mediaController.setMediaPlayer(video_view);// 设置MediaController与VideView建立关联
        video_view.start();// 开始播放

        video_view.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                video_view.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/raw/vv"));
                video_view.start();
            }
        });

        mGestureDetector = new GestureDetector(this);

    }

    public void openVideo() {
        resideLayout.openPane();
    }

    /**
     * 绘制底部UI
     */
    private void initBootomUI() {
        //创建底部tab
        String[] text_bottom = {"学习", "论坛", "主页", "招聘", "我的"};
        int[] seled = {R.mipmap.main_nav_icon2_select_temp, R.mipmap.main_nav_icon2_select_temp, R.mipmap.main_nav_icon2_select_temp, R.mipmap.main_nav_icon2_select_temp, R.mipmap.main_nav_icon2_select_temp};
        int[] disseled = {R.mipmap.main_nav_icon2_unselect_temp, R.mipmap.main_nav_icon2_unselect_temp, R.mipmap.main_nav_icon2_unselect_temp, R.mipmap.main_nav_icon2_unselect_temp, R.mipmap.main_nav_icon2_unselect_temp};
        BootomTabUtils bootomTabUtils = new BootomTabUtils();
        bootomTabUtils.editBootomView(R.layout.activity_main, this, seled, disseled, text_bottom, 2);
        bootomTabUtils.listenerClick(new BootomTabUtils.Listener() {
            @Override
            public void clickTab1(View view, int tabIndex, String tabTest) {
                supportFragmentManager.beginTransaction().hide(home_fragment).commit();
                supportFragmentManager.beginTransaction().hide(liveFragment).commit();
                supportFragmentManager.beginTransaction().show(studyFragment).commit();
                supportFragmentManager.beginTransaction().hide(userFragment).commit();
                supportFragmentManager.beginTransaction().hide(catory_fragment).commit();
            }

            @Override
            public void clickTab2(View view, int tabIndex, String tabTest) {
                supportFragmentManager.beginTransaction().hide(home_fragment).commit();
                supportFragmentManager.beginTransaction().hide(liveFragment).commit();
                supportFragmentManager.beginTransaction().show(catory_fragment).commit();
                supportFragmentManager.beginTransaction().hide(userFragment).commit();
                supportFragmentManager.beginTransaction().hide(studyFragment).commit();
            }

            @Override
            public void clickTab3(View view, int tabIndex, String tabTest) {
                supportFragmentManager.beginTransaction().show(home_fragment).commit();
                supportFragmentManager.beginTransaction().hide(liveFragment).commit();
                supportFragmentManager.beginTransaction().hide(catory_fragment).commit();
                supportFragmentManager.beginTransaction().hide(userFragment).commit();
                supportFragmentManager.beginTransaction().hide(studyFragment).commit();
            }

            @Override
            public void clickTab4(View view, int tabIndex, String tabTest) {
                supportFragmentManager.beginTransaction().hide(home_fragment).commit();
                supportFragmentManager.beginTransaction().show(liveFragment).commit();
                supportFragmentManager.beginTransaction().hide(catory_fragment).commit();
                supportFragmentManager.beginTransaction().hide(userFragment).commit();
                supportFragmentManager.beginTransaction().hide(studyFragment).commit();
            }

            @Override
            public void clickTab5(View view, int tabIndex, String tabTest) {
                supportFragmentManager.beginTransaction().hide(home_fragment).commit();
                supportFragmentManager.beginTransaction().hide(liveFragment).commit();
                supportFragmentManager.beginTransaction().hide(catory_fragment).commit();
                supportFragmentManager.beginTransaction().show(userFragment).commit();
                supportFragmentManager.beginTransaction().hide(studyFragment).commit();
            }
        });
    }


    @Override
    protected void initData() {
//        ToStartActivity(dfsfdsd.class);
    }


    @Override
    protected boolean leftIconClickListener(View view) {
//        Toast.makeText(this, "11111", Toast.LENGTH_SHORT).show();

        ToStartActivity(CustomView.class);

        return false;
    }

    @Override
    protected boolean rightIconClickListener(View view) {
//        ToStartActivity(MessageActivity.class);
        GalleryActivity.openActivity(this, true, 1);
        return false;
    }


    @Override
    public void onClick(View view) {

    }

    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {

    }

    @Override
    public void onSwipeBackLayoutCancel() {

    }

    public void setMangager(String tag) {
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        BaseFragment fragmentByTag = (BaseFragment) supportFragmentManager.findFragmentByTag(tag);
        fragmentByTag.setFunctionManager(FunctionManager.getInstance().addFunction(new Children1("abc") {
            @Override
            public void funtion() {
                Toast.makeText(MainActivity.this, "abc", Toast.LENGTH_SHORT).show();
            }
        }));
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == -1) {
            Uri uri = data.getData();

            try {
                if (requestCode == 1) {
                    List<String> photos = (List<String>) data.getSerializableExtra(GalleryActivity.PHOTOS);
                    String pathDiv = photos.get(0);
                    file = compression(pathDiv, uri);
                    Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
//                    imggggg.setImageBitmap(bitmap);
                    My my = new My();
                    my.start();
                }
            } catch (Exception e) {

                Log.e("", "异常" + e);
            }
        }

    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    private static final int FLING_MIN_DISTANCE = 50;
    private static final int FLING_MIN_VELOCITY = 0;


    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float v1) {

        if (e1.getY() - e2.getY() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            // Fling left
            Toast.makeText(this, "向上手势", Toast.LENGTH_SHORT).show();
        } else if (e2.getY() - e1.getY() > FLING_MIN_DISTANCE
                && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            // Fling right
            Toast.makeText(this, "向下手势", Toast.LENGTH_SHORT).show();
        }
        Log.e("onFling", "onFling");

        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return mGestureDetector.onTouchEvent(motionEvent);
    }

    class My extends Thread {
        @Override
        public void run() {

//            String upurl = new AppConfig(UpUserInfoActivity.this).getRestfulServer_new() + "image/upload_logo";
            String upurl = "http://shop.tenfeiba.com/anpai/php/Imp_manager/uploadImg.php";
            Log.e("", "-----------++++++++++++++++++++" + upurl);
            upload(upurl, file, null, new FileUploadListener() {
                @Override
                public void onProgress(long pro, double precent) {

                }  //

                @Override
                public void onFinish(int code, String res, Map<String, List<String>> headers) {
                    Log.e("", "得到返回码" + code);
                    Log.e("", "得到返回路径" + res);
                    Log.e("", "得到返回集合" + headers);
                }
            });
        }
    }

    public interface FileUploadListener {
        public void onProgress(long pro, double precent);

        public void onFinish(int code, String res, Map<String, List<String>> headers);
    }


    /**
     * 上传图片方法
     *
     * @param host
     * @param file
     * @param params
     * @param listener
     */
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    private static final String PREFIX = "--";
    private static final String LINE_END = "\r\n";

    public static void upload(String host, File file, Map<String, String> params, FileUploadListener listener) {
        String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(host);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", CHARSET);//设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            conn.setDoInput(true); //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false); //不允许使用缓存
            if (file != null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(LINE_END);
                if (params != null) {//根据格式，开始拼接文本参数
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);//分界符
                        sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINE_END);
                        sb.append("Content-Type: text/plain; charset=" + CHARSET + LINE_END);
                        sb.append("Content-Transfer-Encoding: 8bit" + LINE_END);
                        sb.append(LINE_END);
                        sb.append(entry.getValue());
                        sb.append(LINE_END);//换行！
                    }
                }
                sb.append(PREFIX);//开始拼接文件参数
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意：
                 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
                 * filename是文件的名字，包含后缀名的 比如:abc.png
                 */
                sb.append("Content-Disposition: form-data; name=\"name\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
                sb.append(LINE_END);
                //写入文件数据
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                long totalbytes = file.length();
                long curbytes = 0;
                Log.i("cky", "total=" + totalbytes);
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    curbytes += len;
                    dos.write(bytes, 0, len);
                    listener.onProgress(curbytes, 1.0d * curbytes / totalbytes);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int code = conn.getResponseCode();
                sb.setLength(0);
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                listener.onFinish(code, sb.toString(), conn.getHeaderFields());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 图片按比例大小压缩方法
     *
     * @param srcPath （根据路径获取图片并压缩）
     * @return
     */
    public File compression(String srcPath, Uri uri) {

        //String edpath = Environment.getExternalStorageDirectory() + filename + ".png";
        int i = readPictureDegree(srcPath); //获取角度 三星手机适配
        Log.e("", "旋转前" + i);
/*        Bitmap bitMBitmap = getBitmapFromUri(uri); //获取bitmap

        int i5 = readPictureDegree(srcPath); //获取角度 三星手机适配
        Log.e("", "旋转后" + i5);*/
        //sava(rotaingedBitmap); //保存
        // File file = new File(getSDCardPath() + "/AndyDemo/ScreenImage");
        //Log.e("是否存在","是否存在"+file.isFile());

        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;// 这里设置高度为800f
        float ww = 480f;// 这里设置宽度为480f
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        bitmap = rotaingImageView(i, bitmap);  //旋转后图片
        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
    }


    /**
     * 压缩图片（质量压缩）
     *
     * @param bitmap
     */
    public File compressImage(Bitmap bitmap) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 200) {  //循环判断如果压缩后图片是否大于200kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
//                BAFLogger.e(TAG,e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
//            BAFLogger.e(TAG,e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        Log.e("", "压缩之后的文件大小" + file.length());
        return file;
    }


    /**
     * 释放
     *
     * @param bitmaps
     */
    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }


    /**
     * 三星手机适配（图片旋转90度问题） ==========找到被旋转角度
     * 读取图片属性：旋转的角度 int degree = readPictureDegree(ss);
     *
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /**
     * 三星手机适配（图片旋转90度问题） ==========图片回正
     * 读取图片属性：旋转的角度 int degree = readPictureDegree(ss);
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();

        matrix.postRotate(angle);
        System.out.println("angle2=" + angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * 4.4以上系统 uri获得
     * @param requestCode
     * @param resultCode
     * @param data
     */
    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public String getHightPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    /**
     * 4.4及以下系统 uri获得
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getLowPath(final Context context, final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    /**
     * 版本号判断
     *
     * @return
     */
    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(Build.VERSION.SDK);

        } catch (NumberFormatException e) {
        }
        return version;
    }


    /**
     * 通过uri得到path地址情况分类
     */
    public String getPathDiv(Uri uri) {
        String path;
        if (getAndroidSDKVersion() > 19) {    //安卓4.4之上
            path = getHightPath(getBaseContext(), uri);
            Log.e("版本判断", "》19");
            return path;
        } else {                          //安卓4.4及之下
            path = getLowPath(getBaseContext(), uri);
            Log.e("版本判断", "《=19");
            return path;
        }
    }


}
